package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.hmdp.utils.RedisConstants.SHOP_TYPE_LIST;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<ShopType> queryTypeList() {
        //1.查询redis缓存
        List<String> list = stringRedisTemplate.opsForList().range(SHOP_TYPE_LIST, 0, -1);
        ArrayList<ShopType> shopTypeList = new ArrayList<>();
        if (null!= list) {
            for (String shop : list) {
                ShopType shopType = JSONUtil.toBean(shop, ShopType.class);
                shopTypeList.add(shopType);
            }
        }



        //2.判断list返回是否为空 非空返回
        if (!shopTypeList.isEmpty()) {
            return shopTypeList;
        }

        //3.空则查询mysql
        List<ShopType> shopTypes = list();

        //4.判断mysql返回是否为空
        if (shopTypes.isEmpty()) {
            //5.空则报错
            Result.fail("没有商户列表信息");
        }


        //6.非空则将list存入redis
        ArrayList<String> shopsStrList = new ArrayList<>();
        for (ShopType shopType : shopTypes) {
            String s = JSONUtil.toJsonStr(shopType);
            shopsStrList.add(s);
        }
        Long aLong = stringRedisTemplate.opsForList().rightPushAll(SHOP_TYPE_LIST, shopsStrList);

        //7.返回


        return shopTypes;
    }
}
